package cn.wzptsoft.tinymallbe.service;

import cn.wzptsoft.tinymallbe.entity.Category;
import cn.wzptsoft.tinymallbe.entity.Spu;
import cn.wzptsoft.tinymallbe.repository.CategoryRepository;
import cn.wzptsoft.tinymallbe.repository.SpuRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SpuService {
    private final SpuRepository spuRepository;
    private final CategoryRepository categoryRepository;

    public SpuService(SpuRepository spuRepository, CategoryRepository categoryRepository) {
        this.spuRepository = spuRepository;
        this.categoryRepository = categoryRepository;
    }

    /**
     * 商品列表分页查询
     */
    public Page<Spu> getSpuByPage(Integer pageNum, Integer size) {
        Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
        return spuRepository.findAll(page);
    }

    /**
     * 查找指定商品的详情
     *
     * @param id 商品ID
     * @return 商品详情
     */
    @Transactional
    public Spu getSpu(Long id) {
        return spuRepository.getById(id);
    }

    /**
     * 查找指定商品分类下的商品
     *
     * @param categoryId 商品类别ID
     * @param isRoot     是否为根分类
     * @param pageNum    当前分页
     * @param size       每页数据条数
     * @return 分页后的商品
     */
    public Page<Spu> getByCategory(Long categoryId, Boolean isRoot, Integer pageNum, Integer size) {
        Pageable page = PageRequest.of(pageNum, size, Sort.by("createTime").descending());
        Page<Spu> pageResult;
        // 如果不是根分类 直接以categoryId为条件进行查询
        if (!isRoot) {
            pageResult = spuRepository.findByCategoryId(categoryId, page);
        } else {
            // 如果是根分类 则先查出根分类下的二级分类 再以二级分类为条件进行查询
            List<Category> subCategory = categoryRepository.findByParentId(categoryId);
            // List<Category> ---> List<Long>
            List<Long> subCategoryIds = subCategory.stream().map(Category::getId).collect(Collectors.toList());
            pageResult = spuRepository.findByCategoryIdIn(subCategoryIds, page);
        }
        return pageResult;
    }
}
